<template>
  <!-- 标准检验规则表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    @close="closeDialog"
  >
    <el-form
      v-show="!props.isReadonly"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="规则规范码" prop="ruleCode">
            <el-input
              v-model="formData.ruleCode"
              placeholder="请输入规则规范码"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-model="formData.ruleName"
              placeholder="请输入规则名称"
              clearable
            />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="操作类型" prop="opeTypeCode">-->
<!--            <el-select-->
<!--              style="width: 100%"-->
<!--              v-model="formData.opeTypeCode"-->
<!--              placeholder="请选择操作类型"-->
<!--              :disabled="isBind"-->
<!--              @change="changeOperateType"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in dictionaryStore.filterDictList(-->
<!--                  'CheckOperateType'-->
<!--                )"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="事务类型" prop="effectTypeCode">-->
<!--            <el-select-->
<!--              style="width: 100%"-->
<!--              v-model="formData.effectTypeCode"-->
<!--              placeholder="请选择事务类型"-->
<!--              :disabled="isBind"-->
<!--              @change="changeEffectType"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in effectTypeCodeList"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="检验类型" prop="effectCheckTypeId">-->
<!--            <el-select-->
<!--              style="width: 100%"-->
<!--              v-model="formData.effectCheckTypeId"-->
<!--              :disabled="isBind"-->
<!--              placeholder="请选择检验类型"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in effectCheckTypeList"-->
<!--                :key="item.id"-->
<!--                :label="item.checkTypeName"-->
<!--                :value="item.id"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->

<!--        <el-col :span="12">-->
<!--          <el-form-item label="检验级别" prop="effectLevelCode">-->
<!--            <el-select-->
<!--              style="width: 100%"-->
<!--              v-model="formData.effectLevelCode"-->
<!--              placeholder="请选择检验级别"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in dictionaryStore.filterDictList('EffectLevel')"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="连续检验个数" prop="checkNum">
            <el-input
              v-model="formData.checkNum"
              placeholder="请输入连续检验个数"
            >
              <template #append>个</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抽点检频次" prop="checkFrequency">
            <el-input
              v-model="formData.checkFrequency"
              placeholder="请输入抽点检频次"
            >
              <template #append>小时</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="周期个数" prop="weekNum">
            <el-input v-model="formData.weekNum" placeholder="请输入周期个数">
              <template #append>班次</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top w-full"
      title=""
      :column="1"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">规则规范码</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.ruleCode || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">规则名称</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.ruleName || "" }}
        </div>
      </el-descriptions-item>
<!--      <el-descriptions-item>-->
<!--        <template #label>-->
<!--          <div class="cell-item">操作类型</div>-->
<!--        </template>-->
<!--        <div style="width: 100%; word-break: break-all">-->
<!--          {{ useDictionary("CheckOperateType", formData.opeTypeCode) || "" }}-->
<!--        </div>-->
<!--      </el-descriptions-item>-->
<!--      <el-descriptions-item>-->
<!--        <template #label>-->
<!--          <div class="cell-item">事务类型</div>-->
<!--        </template>-->
<!--        <div style="width: 100%; word-break: break-all">-->
<!--          {{ getEffectTypeCode(formData) }}-->
<!--        </div>-->
<!--      </el-descriptions-item>-->
<!--      <el-descriptions-item>-->
<!--        <template #label>-->
<!--          <div class="cell-item">检验类型</div>-->
<!--        </template>-->
<!--        <div style="width: 100%; word-break: break-all">-->
<!--          {{ formData.checkTypeName || "" }}-->
<!--        </div>-->
<!--      </el-descriptions-item>-->
<!--      <el-descriptions-item>-->
<!--        <template #label>-->
<!--          <div class="cell-item">连续检验个数</div>-->
<!--        </template>-->
<!--        <div style="width: 100%; word-break: break-all">-->
<!--          {{ formData.checkNum || "" }}-->
<!--        </div>-->
<!--      </el-descriptions-item>-->
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">抽点检频次</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkFrequency || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">周期个数</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.weekNum || "" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
import { checkCommon } from "@/views/qms/checkHook/checkCommon";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSCHECKRULEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const isBind = ref(false);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

function validateNumber(rule: any, value: any) {
  if (value === "" || value === null || value === undefined)
    return Promise.resolve();
  if (!/^\d+$/.test(value)) return Promise.reject("请输入大于0的数字");
  return Promise.resolve();
}

const rules = reactive({
  ruleCode: [
    { required: true, message: "请输入规则编码", trigger: ["blur", "change"] },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  ruleName: [
    { required: true, message: "请输入规则名称", trigger: ["blur", "change"] },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  // effectTypeCode: [
  //   { required: true, message: "请选择事务类型", trigger: ["blur", "change"] },
  // ],
  // effectLevelCode: [
  //   { required: true, message: "请选择检验级别", trigger: ["blur", "change"] },
  // ],
  // effectCheckTypeId: [
  //   { required: true, message: "请选择检验类型", trigger: ["blur", "change"] },
  // ],
  checkNum: [{ validator: validateNumber, trigger: ["blur", "change"] }],
  checkFrequency: [{ validator: validateNumber, trigger: ["blur", "change"] }],
  weekNum: [{ validator: validateNumber, trigger: ["blur", "change"] }],
  // opeTypeCode: [
  //   { required: true, message: "请选择操作类型", trigger: ["blur", "change"] },
  // ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  ruleCode: "",
  ruleName: "",
  effectTypeCode: "",
  effectLevelCode: "",
  effectCheckTypeId: "",
  checkTypeName: "",
  checkNum: "",
  checkFrequency: "",
  weekNum: "",
  opeTypeCode: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});
const { changeOpeType, getEffectTypeCode, effectTypeCodeList } = checkCommon(
  ref(formData)
);
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        ruleCode,
        ruleName,
        effectTypeCode,
        effectLevelCode,
        effectCheckTypeId,
        checkTypeName,
        checkNum,
        checkFrequency,
        weekNum,
        opeTypeCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        bind,
      } = newVal;
      changeOperateType(opeTypeCode);
      changeEffectType(effectTypeCode, opeTypeCode);
      isBind.value = bind;
      Object.assign(formData, {
        id,
        version,
        ruleCode,
        ruleName,
        effectTypeCode,
        effectLevelCode,
        effectCheckTypeId,
        checkTypeName,
        checkNum,
        checkFrequency,
        weekNum,
        opeTypeCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  effectTypeCodeList.value = [];
  effectCheckTypeList.value = [];
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.ruleCode = "";
  formData.ruleName = "";
  formData.effectTypeCode = "";
  formData.effectLevelCode = "";
  formData.effectCheckTypeId = "";
  formData.checkNum = "";
  formData.checkFrequency = "";
  formData.weekNum = "";
  formData.opeTypeCode = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  isBind.value = false;
}

const loading = ref(false);

/** 标准检验规则保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmscheckrule/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const changeOperateType = (val) => {
  formData.effectCheckTypeId = "";
  effectCheckTypeList.value = [];
  changeOpeType(val);
};
const effectCheckTypeList = ref([]);

const changeEffectType = async (val, opeTypeCode) => {
  formData.effectCheckTypeId = "";
  const { data } = await request({
    url: "/qms/qmschecktype/getList",
    method: "post",
    data: {
      opeTypeCode: opeTypeCode ?? formData.opeTypeCode,
      effectTypeCode: val,
    },
  });
  effectCheckTypeList.value = data;
};
</script>
